package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021/8/16.<br><br>
 *
 * 中等：字符串转换整数 (atoi)
 */
public class Topic8 {

    public static void main(String[] args) {
        Topic8 instance = new Topic8();

        System.out.println(instance.myAtoi("42"));
        System.out.println(instance.myAtoi("   -42"));
        System.out.println(instance.myAtoi("4193 with words"));
        System.out.println(instance.myAtoi("words and 987"));
        System.out.println(instance.myAtoi("-91283472332"));
        System.out.println(instance.myAtoi("+1"));
        System.out.println(instance.myAtoi("-2147483647"));
    }

    public int myAtoi(String s) {
        s = s.trim();
        if(s.length() < 1) {
            return 0;
        }

        char[] array = s.toCharArray();
        boolean sign = array[0] == '-';

        long result = 0;
        int i = (array[0] == '-' || array[0] == '+') ? 1 : 0;
        for(; i < array.length; i++) {
            if(Character.isDigit(array[i])) {
                result *= 10;
                result += array[i] - '0';

                if(result > Integer.MAX_VALUE) {
                    return sign ? Integer.MIN_VALUE : Integer.MAX_VALUE;
                }
            }
            else {
                break;
            }
        }

        return (int) (sign ? -result : result);
    }
}
